package com;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树的前序遍历
 * User: YJ
 * Date: 2024-4-01
 * Time: 21:25
 */


class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}


public class preorderTraversalExer {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param root TreeNode类
     * @return int整型一维数组
     */
    public static int[] preorderTraversal(TreeNode root) {
        // write code here
        List<Integer> list = new ArrayList<>();
        //递归添加节点值到list集合中
        preOrder(list,root);
        //遍历集合中的值
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }

    private static void preOrder(List<Integer> list, TreeNode root) {
        //空节点返回
        if (root == null) return;
        //根
        list.add(root.val);
        //左
        preOrder(list,root.left);
        //右
        preOrder(list,root.right);
    }
}
